package models

import (
	"database/sql"

	"gitee.com/sansaniot/ssiot-core/httpmvc/model"
	"gorm.io/datatypes"

	cDto "ssalarm/common/dto"
	"ssalarm/internal/alarm/models/query"
)

type SysDev struct {
	Id           string         `json:"id" gorm:"primaryKey;type:varchar(255);comment:id"`
	Sn           string         `json:"sn" gorm:"type:varchar(255);comment:设备序列号"`
	Name         string         `json:"name" gorm:"type:varchar(255);comment:设备名称"`
	DeptId       string         `json:"deptId" gorm:"type:varchar(255);comment:分组id"`
	OnlineStatus string         `json:"onlineStatus" gorm:"type:varchar(255);comment:在线状态"`
	Type         string         `json:"type" gorm:"type:varchar(255);comment:类型"`
	ProductCode  string         `json:"productCode" gorm:"type:varchar(255);comment:产品编码"`
	GatewaySn    string         `json:"gatewaySn" gorm:"type:varchar(255);comment:网关SN"`
	AlarmStatus  bool           `json:"alarmStatus" gorm:"type:bool;comment:是否告警"`
	Location     datatypes.JSON `json:"location" gorm:"type:jsonb;comment:地址经纬度"`

	CreateTime   *cDto.LocalTime `json:"createTime" gorm:"type:timestamptz(6);comment:创建时间"`
	UpdateTime   *cDto.LocalTime `json:"updateTime" gorm:"type:timestamptz(6);comment:更新时间"`
	LastLiveTime *cDto.LocalTime `json:"lastLiveTime" gorm:"type:timestamptz(6);comment:末次交互时间"`
	RegisterTime *cDto.LocalTime `json:"registerTime" gorm:"type:timestamptz(6);comment:注册时间"`
	LogoutTime   *cDto.LocalTime `json:"logoutTime" gorm:"type:timestamptz(6);comment:登出时间"`

	model.Model

	DeptName string                 `json:"deptName" gorm:"-"`
	SvcInfo  map[string]interface{} `json:"svcInfo" gorm:"-"`
}

func (SysDev) TableName() string {
	return "sys_dev"
}

func (e *SysDev) Generate() interface{} {
	o := *e
	return &o
}

func (e *SysDev) GetId() interface{} {
	return e.Id
}

func (e *SysDev) FindDevice(req *query.SysDevQuery) (err error, one SysDev) {
	err = e.FindOne(&one, cDto.MakeCondition(req.GetNeedSearch()))
	return
}

func (e *SysDev) UpdateAlarmStatus(alarmSnList []string) {
	var devList []SysDev
	if len(alarmSnList) > 0 {
		var alarmGatewayList []string
		//设备sn告警 对应的网关也应该属于告警
		e.Orm.Model(&devList).Where("gateway_sn is not null").Where("gateway_sn != ''").Where("sn in ?", alarmSnList).Distinct().Pluck("gateway_sn", &alarmGatewayList)
		//告警设备和告警网关编号取并集
		alarmSnList = append(alarmSnList, alarmGatewayList...)
	}
	//清除所有告警标志
	e.Orm.Model(e).Where("alarm_status = 't'").Update("alarm_status", sql.NullBool{})
	// 添加指定SN告警标志
	if len(alarmSnList) > 0 {
		e.Orm.Model(e).Where("sn in ?", alarmSnList).Update("alarm_status", true)
	}
}
